package com.pi.shisan.service.util;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

/**
 * 每秒执行一次的守护线程
 * 不需要手动销毁，程序退出自动结束
 */
public class SecondRefreshThreadUtil {

    private static SecondThread thread;

    /**
     * 过期300秒线程销毁，下次使用重新创建
     */
    private final static int timeoutSeconds = 300;

    /**
     * 要执行的任务结束返回false即可
     */
    private final static Map<Supplier<Boolean>,Boolean> ALL = new ConcurrentHashMap<>();

    public static void register(Supplier<Boolean> runnable) {
        ALL.put(runnable,true);
        tryToInitNewThreadAndStart();
    }

    public static void unregister(Supplier<Boolean> runnable) {
        ALL.remove(runnable);
    }

    private static void tryToInitNewThreadAndStart() {
        if (thread == null) {
            synchronized (SecondRefreshThreadUtil.class) {
                if (thread == null) {
                    thread = new SecondThread();
                    thread.setDaemon(true);
                    thread.start();
                }
            }
        } else {
            if (!thread.resetTimes()) {
                synchronized (SecondRefreshThreadUtil.class) {
                    if (!thread.resetTimes()) {
                        thread = new SecondThread();
                        thread.setDaemon(true);
                        thread.start();
                    }
                }
            }
        }
    }

    static class SecondThread extends Thread {
        private int emptyTimes;

        private AtomicInteger status = new AtomicInteger(1);

        @Override
        public void run() {
            while (true) {
                status.compareAndSet(2,1);
                for (Supplier<Boolean> curr : ALL.keySet()) {
                    if (!curr.get()) {
                        ALL.remove(curr);
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
                if (ALL.isEmpty()) {
                    if (emptyTimes ++ >= timeoutSeconds) {
                        if (status.compareAndSet(1,0)) {
                            break;
                        }
                    }
                } else {
                    emptyTimes = timeoutSeconds;
                }
            }
        }

        public boolean resetTimes() {
            this.emptyTimes = timeoutSeconds;
            if (status.compareAndSet(1,2)) {
                return true;
            }
            return status.get() != 0;
        }
    }

}
